package com.example.androidsx;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class ProductListActivity extends AppCompatActivity implements ProductAdapter.OnCartUpdateListener {

    private List<Product> cartItems = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);

        // 初始化Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        // 设置标题
        String categoryName = getIntent().getStringExtra("category_name");
        TextView title = findViewById(R.id.toolbar_title);
        title.setText(categoryName != null ? categoryName : "商品列表");

        ImageButton btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> onBackPressed());

        // 初始化商品数据
        ArrayList<Object> productList = initProductData(categoryName);

        // 设置RecyclerView
        RecyclerView recyclerView = findViewById(R.id.product_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(new ProductAdapter(productList, this, this));

        setupBottomButtons();
    }

    private ArrayList<Object> initProductData(String categoryName) {
        ArrayList<Object> productList = new ArrayList<>();

        if (categoryName != null) {
            switch (categoryName) {
                case "水果类":
                    productList.add(new Product("苹果", "¥12.5/斤", "红富士 脆甜多汁", "apple"));
                    productList.add(new Product("香蕉", "¥6.8/斤", "海南香蕉 自然熟", "banana"));
                    productList.add(new Product("橙子", "¥9.9/斤", "赣南脐橙 酸甜适中", "orange"));
                    productList.add(new Product("草莓", "¥25.0/盒", "奶油草莓 新鲜采摘", "strawberry"));
                    productList.add(new Product("葡萄", "¥15.8/斤", "巨峰葡萄 无籽多汁", "grape"));
                    productList.add(new Product("西瓜", "¥3.5/斤", "宁夏沙地西瓜", "watermelon"));
                    productList.add(new Product("桃子", "¥8.8/斤", "水蜜桃 果肉柔软", "peach"));
                    productList.add(new Product("梨", "¥7.5/斤", "雪梨 润肺止咳", "pear"));
                    productList.add(new Product("芒果", "¥18.8/斤", "泰国金煌芒", "mango"));
                    productList.add(new Product("菠萝", "¥9.9/个", "海南菠萝", "pineapple"));
                    productList.add(new Product("猕猴桃", "¥12.8/盒", "新西兰佳沛", "kiwi"));
                    productList.add(new Product("柠檬", "¥6.5/个", "安岳柠檬", "lemon"));
                    productList.add(new Product("蓝莓", "¥28.0/盒", "智利进口", "blueberry"));
                    productList.add(new Product("樱桃", "¥45.0/斤", "大连美早", "cherry"));
                    productList.add(new Product("石榴", "¥15.0/个", "会理软籽", "pomegranate"));
                    productList.add(new Product("椰子", "¥12.0/个", "泰国香水椰", "coconut"));
                    productList.add(new Product("无花果", "¥22.0/盒", "新鲜采摘", "fig"));
                    productList.add(new Product("番石榴", "¥9.9/斤", "台湾红心", "guava"));
                    productList.add(new Product("木瓜", "¥7.8/斤", "海南红心", "papaya"));
                    productList.add(new Product("火龙果", "¥10.5/个", "越南白心", "dragonfruit"));
                    break;

                case "零食类":
                    productList.add(new Product("薯片", "¥8.5/袋", "烧烤味", "chips"));
                    productList.add(new Product("巧克力", "¥15.0/盒", "德芙丝滑", "chocolate"));
                    productList.add(new Product("饼干", "¥12.8/盒", "夹心饼干", "cookies"));
                    productList.add(new Product("坚果", "¥28.0/罐", "混合坚果", "nuts"));
                    productList.add(new Product("糖果", "¥9.9/袋", "水果味", "candy"));
                    productList.add(new Product("爆米花", "¥7.5/桶", "焦糖味", "popcorn"));
                    productList.add(new Product("曲奇", "¥18.0/盒", "丹麦风味", "biscuit"));
                    productList.add(new Product("牛肉干", "¥25.0/袋", "内蒙古风味", "jerky"));
                    productList.add(new Product("百奇", "¥6.5/盒", "草莓味", "pocky"));
                    productList.add(new Product("椒盐卷饼", "¥10.8/袋", "咸香酥脆", "pretzel"));
                    productList.add(new Product("棉花糖", "¥12.0/袋", "草莓夹心", "marshmallow"));
                    productList.add(new Product("威化饼", "¥8.8/盒", "巧克力味", "wafer"));
                    productList.add(new Product("口香糖", "¥5.5/条", "薄荷味", "gum"));
                    productList.add(new Product("棒棒糖", "¥1.5/支", "水果味", "lollipop"));
                    productList.add(new Product("混合果干", "¥22.0/袋", "多种搭配", "trail_mix"));
                    productList.add(new Product("米饼", "¥9.9/袋", "日式风味", "rice_cracker"));
                    productList.add(new Product("芝士球", "¥15.0/桶", "浓郁芝士", "cheese_puff"));
                    productList.add(new Product("能量棒", "¥8.0/条", "坚果谷物", "energy_bar"));
                    break;

                case "杂货类":
                    productList.add(new Product("洗衣液", "¥35.0/瓶", "薰衣草香", "detergent"));
                    productList.add(new Product("纸巾", "¥12.0/提", "原生木浆", "tissue"));
                    productList.add(new Product("牙刷", "¥9.9/支", "软毛牙刷", "toothbrush"));
                    productList.add(new Product("洗洁精", "¥15.5/瓶", "柠檬清香", "dishsoap"));
                    productList.add(new Product("洗碗海绵", "¥5.0/个", "强力去污", "sponge"));
                    productList.add(new Product("垃圾袋", "¥18.0/卷", "加厚大号", "trash_bag"));
                    productList.add(new Product("脏衣篮", "¥45.0/个", "折叠款", "laundry_basket"));
                    productList.add(new Product("衣架", "¥12.0/10个", "防滑设计", "hanger"));
                    productList.add(new Product("扫把", "¥25.0/把", "塑料手柄", "broom"));
                    productList.add(new Product("拖把", "¥39.0/个", "旋转脱水", "mop"));
                    productList.add(new Product("水桶", "¥15.0/个", "带拧干器", "bucket"));
                    productList.add(new Product("橡胶手套", "¥8.5/双", "加厚耐用", "gloves"));
                    productList.add(new Product("空气清新剂", "¥12.0/瓶", "柠檬香型", "air_freshener"));
                    productList.add(new Product("电池", "¥20.0/4节", "5号碱性", "batteries"));
                    productList.add(new Product("灯泡", "¥9.9/个", "LED节能", "light_bulb"));
                    break;

                case "蔬菜类":
                    productList.add(new Product("西红柿", "¥6.5/斤", "新鲜采摘", "tomato"));
                    productList.add(new Product("黄瓜", "¥5.8/斤", "本地黄瓜", "cucumber"));
                    productList.add(new Product("土豆", "¥4.2/斤", "黄心土豆", "potato"));
                    productList.add(new Product("西兰花", "¥8.9/斤", "有机种植", "broccoli"));
                    productList.add(new Product("胡萝卜", "¥3.8/斤", "新鲜脆甜", "carrot"));
                    productList.add(new Product("洋葱", "¥2.9/斤", "紫皮洋葱", "onion"));
                    productList.add(new Product("青椒", "¥7.5/斤", "微辣适中", "pepper"));
                    productList.add(new Product("生菜", "¥4.5/颗", "脆嫩新鲜", "lettuce"));
                    productList.add(new Product("菠菜", "¥5.8/斤", "嫩叶菠菜", "spinach"));
                    productList.add(new Product("卷心菜", "¥3.2/颗", "本地种植", "cabbage"));
                    productList.add(new Product("香菇", "¥12.8/斤", "新鲜采摘", "mushroom"));
                    productList.add(new Product("茄子", "¥6.2/斤", "紫皮长茄", "eggplant"));
                    productList.add(new Product("芹菜", "¥4.8/斤", "西芹", "celery"));
                    productList.add(new Product("玉米", "¥3.5/根", "甜玉米", "corn"));
                    productList.add(new Product("豌豆", "¥8.8/斤", "荷兰豆", "peas"));
                    productList.add(new Product("四季豆", "¥7.2/斤", "无筋豆", "bean"));
                    productList.add(new Product("大蒜", "¥9.9/斤", "独头蒜", "garlic"));
                    productList.add(new Product("生姜", "¥6.8/斤", "老姜", "ginger"));
                    productList.add(new Product("南瓜", "¥2.8/斤", "贝贝南瓜", "pumpkin"));
                    productList.add(new Product("萝卜", "¥2.5/斤", "白萝卜", "radish"));
                    break;

                case "饮料类":
                    productList.add(new Product("矿泉水", "¥2.0/瓶", "农夫山泉", "water"));
                    productList.add(new Product("可乐", "¥3.5/罐", "可口可乐", "cola"));
                    productList.add(new Product("果汁", "¥8.0/瓶", "橙汁", "juice"));
                    productList.add(new Product("牛奶", "¥6.5/盒", "纯牛奶", "milk"));
                    productList.add(new Product("茶饮", "¥5.0/瓶", "绿茶", "tea"));
                    productList.add(new Product("咖啡", "¥12.0/罐", "拿铁", "coffee"));
                    productList.add(new Product("啤酒", "¥7.5/听", "青岛啤酒", "beer"));
                    productList.add(new Product("汽水", "¥4.5/瓶", "柠檬味", "soda"));
                    productList.add(new Product("功能饮料", "¥6.0/罐", "红牛", "energy_drink"));
                    productList.add(new Product("矿泉水", "¥1.5/瓶", "怡宝", "mineral_water"));
                    break;
            }
        }
        return productList;
    }

    private void setupBottomButtons() {
        Button btnHome = findViewById(R.id.btn_home);
        btnHome.setOnClickListener(v -> {
            Intent intent = new Intent(this, ShopListActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();
        });

        Button btnCart = findViewById(R.id.btn_cart);
        btnCart.setOnClickListener(v -> {
            Toast.makeText(this, "购物车功能开发中", Toast.LENGTH_SHORT).show();
            // 注释掉原来的Intent
            // Intent intent = new Intent(this, CartActivity.class);
            // intent.putExtra("cart_items", new ArrayList<>(cartItems));
            // startActivity(intent);
        });


        Button btnProfile = findViewById(R.id.btn_profile);
        btnProfile.setOnClickListener(v -> {
            startActivity(new Intent(this, AddressActivity.class));
        });

        Button btnCheckout = findViewById(R.id.btn_checkout);
        btnCheckout.setOnClickListener(v -> {
            if (cartItems.isEmpty()) {
                Toast.makeText(this, "请先添加商品到购物车", Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(this, CheckoutActivity.class);
                intent.putExtra("cart_items", new ArrayList<>(cartItems));
                startActivity(intent);
            }
        });
    }


    @Override
    public void onCartUpdated(Object product) {

    }

    @Override
    public void onCartUpdated(com.google.android.gms.analytics.ecommerce.Product product) {

    }

    @Override
    public void onCartUpdated(Product product) {

        boolean exists = false;
        for (Product item : cartItems) {

            if (item.getName().equals(product.getName())) {
                item.setQuantity(product.getQuantity());
                exists = true;
                break;
            }
        }

        if (!exists && product.getQuantity() > 0) {
            cartItems.add(new Product(product));
        }


        cartItems.removeIf(item -> item.getQuantity() <= 0);


        updateCartButton();
    }

    private void updateCartButton() {
        Button btnCart = findViewById(R.id.btn_cart);
        if (cartItems.isEmpty()) {
            btnCart.setText("购物车");
        } else {
            int totalItems = 0;
            for (Product item : cartItems) {
                totalItems += item.getQuantity();
            }
            btnCart.setText(String.format("购物车(%d)", totalItems));
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}